package com.example.nonacademic_education.util;

import com.example.nonacademic_education.constant.Constant;
import com.example.nonacademic_education.data.request.ListData;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author xinmiao
 * @description
 * @date 2023/3/11 11:00
 */
@Component
public class FileUtils {
    public void getFile(String path, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        String p = Constant.proBiologyImagePath + Constant.FILE_PATH;
        File file = new File(p + path);
        long length = file.length();
        response.addHeader("Content-Length", String.valueOf(length));
//        response.addHeader("Content-Disposition",
//                "attachment;filename=" + URLEncoder.encode(path, "utf-8"));
        //表示以二进制流的形式返回
//        response.setContentType("application/octet-stream");
        //设置Content-Disposition为inline
        response.addHeader("Content-Disposition", "inline;filename="
                + URLEncoder.encode(path, "utf-8").replaceAll("\\+", "%20"));
        //下面这行代码是解决浏览器预览文件时中文乱码的
        String type = path.substring(path.lastIndexOf("."));
        type = type.toLowerCase();
        //System.out.println(type);
        //word文件转换
//        if (type.equals(".doc")){
//            //type = "application/msword";
//        }else
        if (type.equals(".docx") || type.equals(".doc")) {
            File pdfDir = new File(p + Constant.PDF_PATH);
            if (!pdfDir.exists()) {
                pdfDir.mkdir();
            }
            //实例化Document类的对象
            Document doc = new Document();
            //加载Word
            doc.loadFromFile(p + path);
            //保存为PDF格式
            path = path.substring(0, path.lastIndexOf(".")) + ".pdf";
            doc.saveToFile(p + Constant.PDF_PATH + path, FileFormat.PDF);
            file = new File(p + Constant.PDF_PATH + path);
            length = file.length();
            //type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            type = "application/pdf";
        }else if (type.equals(".xls")) {
            type = "application/vnd.ms-excel";
        } else if (type.equals(".xlsx")) {
            type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        } else if (type.equals(".ppt")) {
            type = "application/vnd.ms-powerpoint";
        } else if (type.equals(".pptx")) {
            type = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
        } else if (type.equals(".pdf")) {
            type = "application/pdf";
        } else if (type.equals(".png")) {
            type = "image/png";
        } else if (type.equals(".gif")) {
            type = "image/gif";
        } else if (type.equals(".jpeg")) {
            type = "image/jpeg";
        } else if (type.equals(".jpg")) {
            type = "image/jpeg";
        } else {
            type = "text/html";
        }
        response.setContentType(type + ";charset=UTF-8");
        response.addHeader("Content-Length", String.valueOf(length));
        OutputStream outputStream = response.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        FileInputStream inputStream = new FileInputStream(file);
        bis = new BufferedInputStream(inputStream);
        int i = bis.read(buff);
        while (i != -1) {
            outputStream.write(buff, 0, buff.length);
            outputStream.flush();
            i = bis.read(buff);
        }
        bis.close();
        outputStream.close();
    }

    public String addFile(MultipartFile file, String dir) {
        if (file != null) {
            File fileDir = new File(dir);
            if (!fileDir.exists()) {
                fileDir.mkdir();
            }
            String filename=System.currentTimeMillis()%1000L+file.getOriginalFilename();
            try {
                file.transferTo(new File(dir+filename));
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            return filename;
        }
        return null;
    }
    public void downloadFile(String filename, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        File file = new File(Constant.FILE_TEMPLATE_PATH + filename);
        long length = file.length();
        response.addHeader("Content-Length", String.valueOf(length));
        //表示以二进制流的形式返回
        response.setContentType("application/octet-stream");
        //设置Content-Disposition为inline
        response.addHeader("Content-Disposition", "attachment;filename="
                + URLEncoder.encode(filename, "utf-8").replaceAll("\\+", "%20"));
        //下面这行代码是解决浏览器预览文件时中文乱码的
        String type = filename.substring(filename.lastIndexOf("."));
        type = type.toLowerCase();
        response.setContentType(type + ";charset=UTF-8");
        OutputStream outputStream = response.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        FileInputStream inputStream = new FileInputStream(file);
        bis = new BufferedInputStream(inputStream);
        int i = bis.read(buff);
        while (i != -1) {
            outputStream.write(buff, 0, buff.length);
            outputStream.flush();
            i = bis.read(buff);
        }
        bis.close();
        outputStream.close();
    }

    public String updateFiles(MultipartFile file,String dir, String oldFilename) {
        try {
            File oldFile = new File(dir + oldFilename);
            oldFile.delete();
            String filename=System.currentTimeMillis()%1000L+file.getOriginalFilename();
            file.transferTo(new File(dir + filename));
            return filename;
        }catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public Boolean deleteFiles(ListData listData) {
        List<String> paths = listData.getPaths();
        if (paths != null && (!paths.isEmpty())) {
            for (String path : paths) {
                File file = new File(Constant.FILE_PATH + path);
                file.delete();
            }
        }
        return true;
    }

    public Boolean deleteFile(String dir, String filename) {
        File file = new File(dir+filename);
        return file.delete();
    }
    public void downloadNormalFile(String filename, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        File file = new File(filename);
        long length = file.length();
        response.addHeader("Content-Length", String.valueOf(length));
        //表示以二进制流的形式返回
        response.setContentType("application/octet-stream");
        //设置Content-Disposition为inline
        response.addHeader("Content-Disposition", "attachment;filename="
                + URLEncoder.encode(filename.substring(filename.lastIndexOf('/')+1), "utf-8").replaceAll("\\+", "%20"));
        //下面这行代码是解决浏览器预览文件时中文乱码的
//        String type = filename.substring(filename.lastIndexOf(".")+1);
//        type = type.toLowerCase();
//        response.setContentType(type + ";charset=UTF-8");
        OutputStream outputStream = response.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        FileInputStream inputStream = new FileInputStream(file);
        bis = new BufferedInputStream(inputStream);
        int i = bis.read(buff);
        while (i != -1) {
            outputStream.write(buff, 0, buff.length);
            outputStream.flush();
            i = bis.read(buff);
        }
        bis.close();
        outputStream.close();
    }
}
